Source code for hysop.parameters.scalar_parameter
# Copyright (c) HySoP 2011-2024
#
# This file is part of HySoP software.
# See "https://particle_methods.gricad-pages.univ-grenoble-alpes.fr/hysop-doc/"
# for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from hysop.constants import HYSOP_REAL
from hysop.tools.htypes import check_instance
from hysop.parameters.tensor_parameter import TensorParameter
[docs]
class ScalarParameter(TensorParameter):
"""
A scalar parameter is TensorParameter with its shape
set to (1,). A parameter is a value that may change
as simulation advances.
"""
def __new__(cls, name, **kwds):
assert "shape" not in kwds, "Cannot specify shape for a scalar parameter."
obj = super().__new__(cls, name, shape=(1,), **kwds)
return obj
def __init__(self, name, **kwds):
super().__init__(name, shape=(1,), **kwds)
[docs]
def iterviews(self):
"""Iterate over all parameters views to yield scalarparameters."""
yield (None, self)
def _get_value_impl(self):
"""Return the underlying scalar value."""
return self._value[0]
def _set_value_impl(self, value):
"""
Set the underlying scalar value.
Given value can be a scalar or a np.ndarray of shape (1,).
"""
if not isinstance(value, np.ndarray):
assert np.isscalar(value), "value is neither a np.ndarray, nor a scalar."
value = np.asarray([value], dtype=self.dtype)
value = value.reshape((1,))
super()._set_value_impl(value)
[docs]
def __int__(self):
"""Return value as an int."""
return int(self.value)
[docs]
def __float__(self):
"""Return value as a float."""
return float(self.value)
[docs]
def __complex__(self):
"""Return value as a complex."""
return complex(self.value)
[docs]
def long_description(self):
ss = """\
ScalarParameter[name={}]
*dtype: {}
*min_value: {}
*max_value: {}
*ignore_nans: {}
*value: {}
""".format(
self.name,
self.dtype,
self.min_value,
self.max_value,
self.ignore_nans,
self.value,
)
return ss
[docs]
def short_description(self):
attrs = ("name", "dtype", "value")
info = []
for attr in attrs:
val = getattr(self, attr)
if val is not None:
info.append(f"{attr}={val}")
attrs = ", ".join(info)
ss = "ScalarParameter[{}]"
ss = ss.format(attrs)
return ss